<template>
  <div class="outer">
    <!-- 用户面包屑导航栏 -->
    <Breadcrumb :breadcrumbInfo="breadcrumbInfo"></Breadcrumb>
    <!-- 搜索添加区域 -->
    <el-card class="box-card">
      <el-row :gutter="35">
        <el-col :span="15">
          <!-- 搜索框 -->
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            clearable
            v-model="queryInfo.query"
            @change="searchUsers"
            @clear="searchUsers"
          >
            <el-button slot="append" icon="el-icon-search">搜索</el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="dialogFormVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 添加用户Dialong对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="dialogFormVisible"
        @close="addDialongClose"
      >
        <el-form
          :model="addUerInfo"
          :label-width="formLabelWidth"
          :rules="formFules"
          status-icon
          ref="addFormRef"
        >
          <el-form-item label="用户名称" prop="username">
            <el-input
              v-model="addUerInfo.username"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="用户密码"
            :label-width="formLabelWidth"
            prop="password"
          >
            <el-input
              v-model="addUerInfo.password"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
            <el-input v-model="addUerInfo.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="手机号"
            :label-width="formLabelWidth"
            prop="mobile"
          >
            <el-input v-model="addUerInfo.mobile" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="danger" @click="addDialongClose">重 置</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>

    <!-- 用户列表区 -->
    <el-table :data="userList" stripe border highlight-current-row>
      <el-table-column type="index"></el-table-column>
      <el-table-column prop="username" label="姓名" width="180">
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"> </el-table-column>
      <el-table-column prop="mobile" label="电话"> </el-table-column>
      <el-table-column prop="role_name" label="角色" width="180">
      </el-table-column>
      <el-table-column prop="mg_state" label="状态" width="180">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="switchChanged(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <!-- 操作部分 -->
      <el-table-column label="操作" width="200px">
        <!-- 编辑 删除 分配角色 三个按钮 -->
        <template slot-scope="scope">
          <!-- 编辑按钮 -->
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="getEditForm(scope.row.id)"
          ></el-button>
          <!-- 删除按钮 -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteForm(scope.row.id)"
          ></el-button>
          <!-- 分配角色按钮 -->
          <el-tooltip content="分配角色" placement="top" :enterable="false">
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="assignRoles(scope.row)"
            >
            </el-button>
          </el-tooltip>

          <!-- 编辑dialog表单区 -->
          <el-dialog
            title="用户编辑"
            width="30%"
            :visible.sync="editDialogVisible"
          >
            <el-form
              :label-width="formLabelWidth"
              :model="editUerInfo"
              :rules="formFules"
              status-icon
            >
              <el-form-item label="姓  名" :label-width="formLabelWidth">
                <el-input disabled v-model="editUerInfo.username"></el-input>
              </el-form-item>
              <el-form-item
                label="邮  箱"
                :label-width="formLabelWidth"
                prop="email"
              >
                <el-input
                  autocomplete="off"
                  v-model="editUerInfo.email"
                ></el-input>
              </el-form-item>
              <el-form-item
                label="手机号码"
                :label-width="formLabelWidth"
                prop="mobile"
              >
                <el-input
                  autocomplete="off"
                  v-model="editUerInfo.mobile"
                ></el-input>
              </el-form-item>
            </el-form>
            <!-- 编辑表单提交 -->
            <span slot="footer" class="dialog-footer">
              <el-button @click="editDialogVisible = false">取 消</el-button>

              <el-button type="primary" @click="upDataEditForm"
                >确 定</el-button
              >
            </span>
          </el-dialog>
          <!-- 分配角色dialog对话框 -->
          <el-dialog
            title="分配角色"
            :visible.sync="assignRolesInfo.isShow"
            width="30%"
            @close="setRolesRightsDialogClose"
          >
            <p>当前用户 : {{ assignRolesInfo.userInfo.username }}</p>
            <br />
            <p>当前的角色 : {{ assignRolesInfo.userInfo.role_name }}</p>
            <br />
            分配信息:<el-select
              clearable
              v-model="assignRolesInfo.saveRolesID"
              placeholder="请选择"
            >
              <el-option
                v-for="item in assignRolesInfo.roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <span slot="footer" class="dialog-footer">
              <el-button @click="assignRolesInfo.isShow = false"
                >取 消</el-button
              >
              <el-button type="primary" @click="updataassignRoles"
                >确 定</el-button
              >
            </span>
          </el-dialog>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页功能 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 3, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { validateEMail, validatePhone } from "../../common/regexp";
// 引入面包屑组件
import Breadcrumb from "../../components/Breadcrumb.vue";
export default {
  name: "Name",
  // 父组件
  components: {
    Breadcrumb,
  },
  data() {
    return {
      // 面包屑导航消息
      breadcrumbInfo: {
        titlePath: [
          { title: "首页", Path: "/Home" },
          { title: "用户管理", Path: "" },
          { title: "用户列表", Path: "" },
        ],
      },
      //  请求参数对象
      queryInfo: {
        query: "",
        //当前页数
        pagenum: 1,
        //当前页显示最大是数据
        pagesize: 2,
      },
      // 添加用户信息
      addUerInfo: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      //编辑用户信息
      editUerInfo: {
        email: "",
        mobile: "",
      },
      userList: [],
      total: 0,
      //   表单初始验证
      formFules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 1, max: 5, message: "长度在 1 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 16,
            message: "长度在 3 到 16 个字符",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            validator: validateEMail,
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            validator: validatePhone,
            trigger: "blur",
          },
        ],
      },

      //分配角色的数据信息
      assignRolesInfo: {
        isShow: false,
        // 用户信息
        userInfo: {},
        // 角色列表信息
        roleList: {},
        // 选择的id值
        saveRolesID: "",
      },
      // Dialong对话框
      dialogFormVisible: false,
      editDialogVisible: false,
      // Dialong对话框的宽
      formLabelWidth: "120px",
    };
  },
  methods: {
    // 添加用户方法
    addUser() {
      //表单初步验证
      this.$refs.addFormRef.validate((status) => {
        if (!status) return;
      });
      //  向服务器添加
      this.$http
        .post("/users", {
          username: this.addUerInfo.username,
          password: this.addUerInfo.password,
          email: this.addUerInfo.email,
          mobile: this.addUerInfo.mobile,
        })
        .then(
          (response) => {
            if (response.data.meta.status !== 201) {
              return this.$message.error(response.data.meta.msg);
            }
            //创建成功
            this.$message.success(response.data.meta.msg);
            this.getUrlList();
            //关闭注册框
            this.dialogFormVisible = false;
          },
          (error) => {
            console.log(error.message);
          }
        );
    },
    // 编辑用户信息
    getEditForm(id) {
      // 编辑框状态
      this.editDialogVisible = !this.editDialogVisible;
      this.$http.get("/users/" + id).then((response) => {
        if (response.data.meta.status !== 200) {
          return this.$message.error(response.data.meta.msg);
        }
        // 通过id获取用户成功
        this.editUerInfo = response.data.data;
      });
    },
    //更新用户信息
    upDataEditForm() {
      this.$http
        .put("users/" + this.editUerInfo.id, {
          email: this.editUerInfo.email,
          mobile: this.editUerInfo.mobile,
        })
        .then((response) => {
          if (response.data.meta.status !== 200) {
            return this.$message.error(response.data.meta.msg);
          }
          //   提示更新成功信息
          this.$message.success(response.data.meta.msg);
          // 关闭编辑框
          // 刷新数据列表
          this.getUrlList();
          this.editDialogVisible = false;
        });

      // 关闭编辑框
    },
    // 删除用户
    deleteForm(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http.delete("users/" + id).then((response) => {
            if (response.data.meta.status != 200)
              return this.$message.error(response.data.meta.msg);
            this.getUrlList();
          });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //监听关闭添加表单项重置表单
    addDialongClose() {
      //重置表单
      this.$refs.addFormRef.resetFields();
    },
    //   搜索用户
    searchUsers() {
      this.getUrlList();
    },

    //   改变开关的状态
    switchChanged(switchStatus) {
      this.$http
        .put(`/users/${switchStatus.id}/state/${switchStatus.mg_state}`)
        .then(
          (response) => {
            //表示设置状态失败
            if (response.data.meta.status !== 200) {
              switchStatus.mg_state = !switchStatus.mg_state;
              console.log(response);
              return this.$message.error("设置状态失败");
            }
            this.$message.success("设置状态成功");
          },
          (error) => {
            console.log(error.message);
          }
        );
    },
    //页码发生改变时重新请求刷新页码
    getUrlList() {
      this.$http.get("/users", { params: this.queryInfo }).then(
        (response) => {
          //   获取失败
          if (response.data.meta.status !== 200) {
            return this.$message.error("获取失败,请重新获取");
          }
          this.userList = response.data.data.users;
          this.total = response.data.data.total;
        },
        (error) => {
          console.log(error.message);
        }
      );
    },
    //监听页码改变时会触发
    handleCurrentChange(newPagenum) {
      this.queryInfo.pagenum = newPagenum;
      //   从服务器获取数据
      this.getUrlList();
    },
    //监听页面可以显示大小改变时会触发
    handleSizeChange(newPagesize) {
      this.queryInfo.pagesize = newPagesize;
      //   从服务器获取数据
      this.getUrlList();
    },

    //分配角色操作功能
    async assignRoles(userInfo) {
      // 保存到assignRolesInfo中
      this.assignRolesInfo.userInfo = userInfo;
      //单击分配角色获取角色列表
      const { data: res } = await this.$http.get("roles/");

      if (res.meta.status !== 200) {
        return this.message.error("获取角色列表失败!");
      }
      this.assignRolesInfo.roleList = res.data;
      this.assignRolesInfo.isShow = true;
    },

    //点击按钮分配角色
    async updataassignRoles() {
      if (!this.assignRolesInfo.saveRolesID) {
        return this.$message.error("请选择要分配的角色 ");
      }

      const { data: res } = await this.$http.put(
        `users/${this.assignRolesInfo.userInfo.id}/role`,
        { rid: this.assignRolesInfo.saveRolesID }
      );

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.$message.success("设置角色成功! ");
      // 更新列表
      this.getUrlList();
      this.assignRolesInfo.isShow = false;
    },

    //清空分配表单信息
    setRolesRightsDialogClose() {
      this.assignRolesInfo.userInfo = "";
      this.assignRolesInfo.saveRolesID = "";
    },
  },
  created() {
    //初始化页面
    this.$http.get("/users", { params: this.queryInfo }).then(
      (response) => {
        //   获取失败
        if (response.data.meta.status !== 200) {
          return this.$message.error("获取失败,请重新获取");
        }
        this.userList = response.data.data.users;
        this.total = response.data.data.total;
      },
      (error) => {
        return this.$message.error(error);
      }
    );
  },
};
</script>

<style lang="less" scoped>
.outer {
  height: 100%;
}
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  margin-top: 15px;
  box-shadow: 0 0 0 rgba(0, 0, 0, 0.15);
}
.el-form {
  margin-right: 30px;
}
.el-form-item__label {
  text-align: center;
}
.el-input__inner {
  text-align: center;
}

.el-select {
  margin-left: 20px;
}
</style>